package exhi.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.stp.core.entity.IGridRowFactory;
import com.stp.core.entity.XGrid;
import com.stp.core.entity.XGridPage;
import com.stp.core.entity.XGridRow;
import com.stp.core.entity.XMsg;
import com.stp.core.util.Identities;
import com.stp.rbac.entity.RoleInfo;
import com.stp.rbac.entity.UserInfo;
import com.stp.rbac.manager.RoleMng;
import com.stp.rbac.manager.UserMng;
import com.stp.std.entity.ColumnInfo;
import com.stp.std.manager.ColumnMng;

import exhi.entity.EntpStock;
import exhi.entity.EntpUser;

@Controller
@RequestMapping("/register")
public class EntpRegisterAct extends BaseAct {

	private static final String PATH_REGISTER_INDEX = "/index";

	private static final String PATH_REGISTER_INFO = "/register-info";

	private static final String PATH_REGISTER_SAVE = "/register-save";

	private static final String PATH_REGISTER_FINISH = "/register-finish";

	private static final String PATH_REGISTER_STOCK = "/stock-info";

	private static final String PATH_REGISTER_STOCK_LIST = "/stock-list";

	private static final String PATH_REGISTER_STOCK_DELETE = "/stock-delete";

	private static final String PATH_REGISTER_STOCK_SAVE = "/stock-save";

	private static final String PATH_CORP_MSG = "/corp-msg";

	// 注册首页
	@RequestMapping(PATH_REGISTER_INDEX)
	public void registerIndex(ModelMap model) {
		model.addAttribute("menus", getColumns());
	}

	// 注册信息
	@RequestMapping(PATH_REGISTER_INFO)
	public String registerInfo(@ModelAttribute("entpUser") EntpUser entpUser,
			ModelMap model) {
		model.addAttribute("entpUser", entpUser);
		model.addAttribute("menus", getColumns());
		String entpId;
		if (null == entpUser.getUid() || "".equalsIgnoreCase(entpUser.getUid())) {
			entpId = Identities.uuid();
		} else {
			entpId = entpUser.getUid();
		}
		model.addAttribute("entpId", entpId);
		if ("C".equalsIgnoreCase(entpUser.getDwlx())) {
			return "register/register-c";
		}
		if ("S".equalsIgnoreCase(entpUser.getDwlx())) {
			return "register/register-s";
		}
		if ("X".equalsIgnoreCase(entpUser.getDwlx())) {
			return "register/register-x";
		}
		model.addAttribute("error", "请选择单位类型");
		return PATH_REGISTER_INDEX.substring(1);
	}

	@RequestMapping(PATH_REGISTER_SAVE)
	public String registerSave(HttpServletRequest request,
			@ModelAttribute("entpUser") EntpUser entpUser,
			@RequestParam("entpId") String entpId, ModelMap model)
			throws IllegalStateException, IOException {
		model.addAttribute("menus", getColumns());
		XMsg msg = new XMsg();
		if (null != entpUser.getUid()
				&& !"".equalsIgnoreCase(entpUser.getUid())) {
			entpMng.update(entpUser);
		} else {
			entpMng.save(entpUser);
		}
		String uid = entpUser.getUid();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 执照
		if (saveUpload(multipartRequest, "attach1")) {
			attachMng.saveFileAttach(uid, "CORPCERT0");//
		}
		// 法人身份证
		if (saveUpload(multipartRequest, "attach2")) {
			attachMng.saveFileAttach(uid, "CORPCERT1");
		}
		// 经营人身份证
		if (saveUpload(multipartRequest, "attach3")) {
			attachMng.saveFileAttach(uid, "CORPCERT2");
		}
		String sql = "update t_entp_stock set uid='" + uid + "' where uid='"
				+ entpId + "'";
		entpMng.query(sql);
		model.addAttribute("entpUser", entpUser);
		model.addAttribute("entpId", entpUser.getUid());
		if ("C".equalsIgnoreCase(entpUser.getDwlx())) {
			return "register/check-c";
		}
		if ("S".equalsIgnoreCase(entpUser.getDwlx())) {
			return "register/check-s";
		}
		if ("X".equalsIgnoreCase(entpUser.getDwlx())) {
			return "register/check-x";
		}
		model.addAttribute("error", "请选择单位类型");
		return PATH_REGISTER_INDEX.substring(1);
	}

	// 股权列表
	@RequestMapping(PATH_REGISTER_STOCK_LIST)
	@ResponseBody
	public String stockList(XGridPage page,
			@RequestParam("entpId") String entpId) {
		StockGridRow row = new EntpRegisterAct.StockGridRow();
		String sql = " from EntpStock s where 1=1 ";
		sql += sqlModel.getSQLChars("s.uid", "=", entpId, false, " and ");
		XGrid grid = entpMng.getStockGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	// 股权信息
	@RequestMapping(PATH_REGISTER_STOCK)
	public void stockInfo(@RequestParam("entpId") String entpId,
			@ModelAttribute("entpStock") EntpStock stock, ModelMap model) {
		model.addAttribute("menus", getColumns());
		model.addAttribute("entpId", entpId);
		model.addAttribute("entpStock", stock);
	}

	@RequestMapping(PATH_REGISTER_STOCK_SAVE)
	public String stockSave(HttpServletRequest request,
			@RequestParam("entpId") String entpId,
			@ModelAttribute("entpStock") EntpStock stock, ModelMap model)
			throws IllegalStateException, IOException {
		model.addAttribute("menus", getColumns());
		XMsg msg = new XMsg();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得第1张图片（根据前台的name名称得到上传的文件）
		MultipartFile attach = multipartRequest.getFile("attachment");
		if (null != attach && attach.getSize() > 0) {
			if (attach.getSize() > 5242880) {
				msg.setState(false);
				msg.setMsg("上传附件不能超过5兆");
				model.addAttribute("msg", msg);
				return "msg";
			}
			String path = request.getSession().getServletContext()
					.getRealPath("/attach/"); // 获取文件的保存路径
			String originalFileName = attach.getOriginalFilename(); // 原始的文件名
			String uniqueFileName = entpId + "_"
					+ String.valueOf(System.currentTimeMillis()); // 将文件重新命名，反正重复
			String extensionName = StringUtils.substringAfterLast(
					originalFileName, "."); // 获取扩展名
			List<String> fileTypes = new ArrayList<String>();
			fileTypes.add("jpg");
			fileTypes.add("jpeg");
			fileTypes.add("bmp");
			fileTypes.add("png");
			fileTypes.add("gif");
			if (fileTypes.contains(extensionName.toLowerCase())) {
				attach.transferTo(new File(path + "/" + uniqueFileName + "."
						+ extensionName)); // 文件上传
				stock.setGdsfz("attachment/" + uniqueFileName + "."
						+ extensionName);
			} else {
				msg.setState(false);
				msg.setMsg("不支持此文件类型上传");
				model.addAttribute("msg", msg);
				return "msg";
			}
		}
		if (null == stock.getUid())
			stock.setUid(entpId);
		entpMng.saveStock(stock);
		model.addAttribute("msg", msg);
		return "msg";
	}

	@RequestMapping(PATH_REGISTER_STOCK_DELETE)
	@ResponseBody
	public String delete(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids) {
		delete("t_entp_stock", "id", ids);
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	// 注册结束
	@RequestMapping(PATH_REGISTER_FINISH)
	public void registerFinish(@ModelAttribute("entpUser") EntpUser entpUser,
			ModelMap model) {
		model.addAttribute("menus", getColumns());
		// 转为正式会员管理
		if (null != entpUser) {
			UserInfo user = new UserInfo();
			user.setUserId(entpUser.getUid());
			user.setAccount(entpUser.getZzjgdm());
			user.setPwd(entpUser.getPwd());
			user.setNickName(entpUser.getMc());
			user.setUserStatus("T");
			Set<RoleInfo> roles = new HashSet<RoleInfo>();
			RoleInfo r;
			if (entpUser.getUserType() != null) {
				if ("Z".equalsIgnoreCase(entpUser.getUserType())
						|| "C".equalsIgnoreCase(entpUser.getUserType())) {
					r = roleMng.get("R0003");
					roles.add(r);
				}
				if ("E".equalsIgnoreCase(entpUser.getUserType())
						|| "A".equalsIgnoreCase(entpUser.getUserType())) {
					r = roleMng.get("R0004");
					roles.add(r);
				}
			}
			userMng.save(user, roles);
		}
	}

	@ModelAttribute("entpUser")
	public EntpUser getEntpUser(
			@RequestParam(value = "entpId", required = true, defaultValue = "") String id) {
		EntpUser info = entpMng.get(id);
		if (null == info) {
			info = new EntpUser();
		}
		return info;
	}

	@ModelAttribute("entpStock")
	public EntpStock getEntpStock(
			@RequestParam(value = "stockId", required = true, defaultValue = "0") String id) {
		if ("".equalsIgnoreCase(id))
			id = "0";
		EntpStock info = entpMng.getStock(new Integer(id));
		if (null == info) {
			info = new EntpStock();
		}
		return info;
	}

	class StockGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			if (obj instanceof EntpStock) {
				xrow = new XGridRow();
				EntpStock info = (EntpStock) obj;
				xrow.setId(info.getId().toString());
				List t = new ArrayList();
				t.add("");
				t.add(info.getGdxm());
				t.add(info.getSfzh());
				if (info.getGdsfz() == null
						|| "".equalsIgnoreCase(info.getGdsfz())) {
					t.add("无");
				} else {
					t.add("<a target='blank' href='./" + info.getGdsfz()
							+ "'>【查看】</a>");
				}

				t.add("<a href='#' onclick='changeStock(" + info.getId()
						+ ");'>【编辑】</a>");
				xrow.setData(t);
			}
			return xrow;
		}
	}

	protected List<ColumnInfo> getColumns() {
		return columnMng.findByProperty("status", "T", " sort ");
	}

	@Autowired
	@Qualifier("columnMng")
	private ColumnMng columnMng;

	@Autowired
	@Qualifier("roleMng")
	private RoleMng roleMng;

	@Autowired
	@Qualifier("userMng")
	private UserMng userMng;
}
